package com.library.ui;

import com.library.service.LoginService;

import javax.swing.*;
import java.awt.*;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;

public class LoginFrame extends JFrame {
    private JTextField managerIdField;
    private JPasswordField passwordField;
    private LoginService loginService = new LoginService();

    public LoginFrame() {
        setTitle("管理员登录");
        setSize(300, 200);
        setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
        setLocationRelativeTo(null);
        setLayout(new GridLayout(3, 2));

        JLabel managerIdLabel = new JLabel("管理员编号：");
        managerIdField = new JTextField();
        JLabel passwordLabel = new JLabel("密码：");
        passwordField = new JPasswordField();
        JButton loginBtn = new JButton("登录");

        loginBtn.addActionListener(new ActionListener() {
            @Override
            public void actionPerformed(ActionEvent e) {
                String managerId = managerIdField.getText();
                String password = new String(passwordField.getPassword());

                if (loginService.validateLogin(managerId, password)) {
                    JOptionPane.showMessageDialog(null, "登录成功");
                    dispose();
                    new MainFrame();
                } else {
                    JOptionPane.showMessageDialog(null, "登录失败，请检查管理员编号和密码");
                }
            }
        });

        add(managerIdLabel);
        add(managerIdField);
        add(passwordLabel);
        add(passwordField);
        add(new JLabel());
        add(loginBtn);

        setVisible(true);
    }

    public static void main(String[] args) {
        // 使用 SwingUtilities.invokeLater 确保 GUI 在事件调度线程中创建和更新
        SwingUtilities.invokeLater(() -> new LoginFrame());
    }
}